package com.cndym.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * ip过滤
 * @author 邱凯
 *
 */
public class IPFilterUtil {
	
	private static Logger logger = Logger.getLogger(IPFilterUtil.class);

	private static String[] IPs = null;

	static {
		try {
			Properties properties = new Properties();
			InputStream inputStream = IPFilterUtil.class.getResourceAsStream("/IPFilter.properties");
			inputStream = new FileInputStream(Utils.getClassPath() + "IPFilter.properties");
			properties.load(inputStream);
			String property = new String(properties.getProperty("ip").getBytes(), "utf-8");
			IPs = property.split("@");
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}

	/**
	 * 验证ip是否合法
	 * @param request
	 * @return true说明ip合法， false说明ip不合法
	 */
	public static boolean verifyIP(HttpServletRequest request) {
		return verifyIP(Utils.getIpAddress(request));
	}
	
	/**
	 * 验证ip是否合法
	 * @param ip
	 * @return true说明ip合法， false说明ip不合法
	 */
	public static boolean verifyIP(String ip) {
		for (String regex : IPs) {
			if (Utils.regValidate(ip, regex))
				return true;
		}
		logger.error("IP为：---"+ip+"---入侵系统！！！请及时查询处理！");
		return false;
	}

}
